// map.js
import qqMap from '../../../utils/qqmap'
Page({
  data: {
    latitude: 40.065956,
    longitude: 116.350077,
    markers:[
      {
        id: 1,
      latitude: 40.066031,
      longitude: 116.353771,
      width: 24,
      height: 30,
    },
    {
      id: 2,
      latitude: 40.079537,
      longitude: 116.340202,
      iconPath: '/static/images/marker.png',
      width: 40,
      height: 40,
    },
    ],
    dialogVisible:false,
   
  },
  onLoad({id}){
     // 获取维修详情
     this.getRepairDetail(id)

  },
  async getRepairDetail(id){
    //id 不存在就不必发请求了
    if (!id) return
    // 请求数据接口
    const{code,data:repairDetail}=await wx.http.get('/repair/' + id)
    // 校验接口调用结果
    if(code !==10000)return wx.utils.toast('获取报修详情失败!')
    // 渲染报修详情
    // console.log(repairDetail)
    this.setData({...repairDetail},()=>{
      // 只有在上门中才进行路线规划
      if(this.data.status===2){
        this.getPolyLine()
      }
    })
  },
  getPolyLine(){
  qqMap.direction({
    mode:'driving',
    from:'40.079537,116.340202',
    to:'40.066031,116.353771',
    success:(res)=>{
      var ret =res
      var coors =ret.result.routes[0].polyline,
      pl=[]
      //坐标解压（返回的点串坐标，通过前向差分进行压缩）
      var kr = 1000000
      for (var i = 2; i < coors.length; i++) {
        coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr
      }
      //将解压后的坐标放入点串数组pl中
      for (var i = 0; i < coors.length; i += 2) {
        pl.push({ latitude: coors[i], longitude: coors[i + 1] })
      }
      console.log(pl)
      //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
      this.setData({
        polyline:[
          {
            points:pl,
            colorList:['#ff0000','#00ff00','#0000ff'],
            width:4
          }
        ]
      })
    },
    fail:(error)=>{
      console.error(error)
    },
    complete:(res)=>{
      console.log(res);
    }
  })
  },
  showDialog(){
    this.setData({
      dialogVisible:true
    })
  },
  dialogClose(e){
     e.detail==='confirm'&&this.cancelRepair()
  },
  async cancelRepair(){
    const{code} = await wx.http.put(`/cancel/repaire/${this.data.id}`)
    if(code !==10000)return wx.utils.toast('取消报修失败')
    wx.navigateBack()
  },
  editRepair(){
    wx.navigateTo({
      url: `/repair_pkg/pages/form/index?id=${this.data.id}`,
    })
  }
})
